<template>
  <div class="xxc">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="小智同学"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- 输入框 -->
    <div class="main">
      <ul
        class="talk_list"
        style="top: 0px"
        id="talk_list"
        v-for="(x, index) in chatArr"
        :key="index"
      >
        <li class="left_word" v-if="x.name !== 'me'">
          <img src="./img/person01.png" /> <span>{{ x.msg }}</span>
        </li>
        <li class="right_word" v-else>
          <img src="./img/person02.png" /> <span>{{ x.msg }}</span>
        </li>
      </ul>
      <div class="drag_bar" style="display: none">
        <div
          class="drager ui-draggable ui-draggable-handle"
          style="display: none; height: 412.628px"
        ></div>
      </div>
    </div>

    <!-- 输入框 -->
    <!-- 底部 -->
    <div class="bottom">
      <van-field v-model="msgg" center clearable placeholder="请输入短信验证码">
        <template #button>
          <van-button size="small" type="primary" @click="massge"
            >发送</van-button
          >
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
export default {
  data() {
    return {
      msgg: '',
      socket: null,
      chatArr: [{ name: 'xs', msg: '我是小智，欢迎撩我' }],
    }
  },

  components: {},

  computed: {
    // ...mapState(['user'])
  },
  created() {
    // debugger
    this.socket = io('ws://geek.itheima.net', {
      query: {
        token: this.$store.state.user.token,
      },
      transports: ['websocket'],
    })
    this.socket.on('connect', () => {
      console.log('连接小智')
      console.log(this.$store.state.user.token)
    })
    this.socket.on('message', (obj) => {
      // debugger
      console.log(obj)
      this.chatArr.push({
        name: 'xs',
        msg: obj.msg,
      })
    })
  },
  mounted() {
    // 接收响应
  },

  // watch(){},

  methods: {
    massge() {
      // if (!this.user){
      //     return
      // }
      if (this.msgg.trim().length === 0) {
        return
      }
      this.socket.emit('message', {
        msg: this.msgg,
        timestamp: new Date().getTime(),
      })
      this.chatArr.push({
        name: 'me',
        msg: this.msgg,
      })
      console.log(this.chatArr)
      this.msgg = ''
    },
  },
  destroyed() {
    this.socket.close()
    this.socket = null
  },
}
</script>
<style scoped lang="less">
@import './css/main.css';

.xxc {
  .bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
  }
}
</style>
